var express = require('express');
var router = express.Router();
const moment = require('moment');
//导入 express
//导入 jwt
const jwt = require('jsonwebtoken');
const AccountModel = require('../../models/AccountModel');
const checkLoginMiddleware=require('../../middleware/checkLoginMiddleware')
//导入中间件

//记账本的列表
router.get('/account', checkLoginMiddleware,function (req, res) {
  //读取集合信息
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        res.status(500).send('读取失败');
        return;
      }
      res.render('list', { accounts: data, moment: moment });
    });
});
router.get('/account/create', checkLoginMiddleware,function (req, res) {
  //读取集合信息
  res.render('create');
});
router.post('/account', checkLoginMiddleware,function (req, res) {
  //读取集合信息
  AccountModel.create(
    {
      ...req.body,
      //修改 time的属性的值
      time: moment(req.body.time).toDate(),
    },
    (err, data) => {
      if (err) {
        res.status(500).send('插入失败');
      }
      //成功插入
      res.render('success', { msg: '添加成功哦', url: '/account' });
    }
  );
});

router.get('/account/:id', checkLoginMiddleware,function (req, res) {
  //读取集合信息
  console.log(req.params.id);
  AccountModel.findOneAndDelete({ _id: req.params.id }, (err, data) => {
    if (err) {
      res.status(500).send('删除失败');
      return;
    }
    res.render('success', { msg: '删除成功', url: '/account' });
  });
});

module.exports = router;
